package router

import (
	"github.com/gin-gonic/gin"
	"learn-hub/handler"
	"net/http"
)

func Cors() gin.HandlerFunc {

	return func(c *gin.Context) {
		method := c.Request.Method
		origin := c.Request.Header.Get("Origin")
		if origin != "" {
			c.Header("Access-Control-Allow-Origin", "*")
			c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
			c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization")
			c.Header("Access-Control-Allow-Credentials", "true")
			c.Set("content-type", "application/json")
		}
		//放行所有OPTIONS方法
		if method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
		}
		c.Next()
	}
}

func Init() *gin.Engine {
	r := gin.Default()

	r.Use(Cors())

	r.Static("/static", "./static")

	r.GET("/", func(c *gin.Context) {
		c.String(http.StatusOK, "hello World!")
	})

	//RBAC权限业务
	r.POST("/user/login", handler.UserLogin)          //登录
	r.POST("/user/userRoleAdd", handler.UserRoleAdd)  //用户和角色关联
	r.POST("/user/roleNodeAdd", handler.RoleNodeAdd)  //角色和权限关联
	r.GET("/user/userRoleList", handler.UserRoleList) //用户对应角色列表
	r.GET("/user/roleNodeList", handler.RoleNodeList) //角色对应权限列表
	r.GET("/user/userList", handler.UserList)         //用户列表缓存
	r.GET("/user/userDetail", handler.UserDetail)     //用户详情缓存

	//仓库订单业务

	r.POST("/repo/repoAdd", handler.RepoAdd)
	r.POST("/repo/repoOrderAdd", handler.RepoOrderAdd)
	r.GET("/repo/repoOrderList", handler.RepoOrderList)
	r.GET("/repo/repoOrderDetail", handler.RepoOrderDetail)

	//货物车辆配送订单
	r.POST("/car/carAdd", handler.CarAdd) //车辆添加
	r.POST("/car/carOrderAdd", handler.CarOrderAdd)
	r.GET("/car/carOrderList", handler.CarOrderList)
	r.GET("/car/carOrderDetail", handler.CarOrderDetail)

	//商品管理订单或者售后订单
	r.GET("/good/goodOrderList", handler.GoodOrderList)
	r.GET("/good/goodOrderDetail", handler.GoodOrderDetail)

	//配送订单
	r.GET("/per/perOrderList", handler.PerOrderList)
	r.GET("/per/perOrderDetail", handler.PerOrderDetail)

	r.GET("/bigCar/bigCarOrderList", handler.BigCarOrderList)
	r.GET("/bigCar/bigCarOrderDetail", handler.BigCarOrderDetail)

	return r
}
